<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\admin\controller;

class Customer  extends Base{

    function index() {
        $listInfo = db('c_customer')->paginate(50);
        $page = $listInfo->render();
        $this->assign('list', $listInfo);
        // $this->assign('page', $page);
        return $this->fetch();
    }
    
    // 添加编辑用户
    public function add() {
        // 将创建的目录指向到nas上
        if (IS_POST) {
            $data = input('post.');
            if($data['id']){
                // 编辑 注意字符集的问题
                // 1：用户名不能重复（表）
                // 2：目录名不能重复（目录下）
                $has = db('c_customer')
                        ->where(array('user_name' => $data['user_name']))
                        ->where('id','<>',$data['id'])
                        ->count();
                if ($has) {
                    $this->ajaxError('用户名已经存在，请重设！');
                    exit;
                }

                // 获取用户的dir_path，并拼接新的用目录
                $customer = db('c_customer')->where('id', $data['id'])->find();
                $namePath = explode(DS, $customer['dir_path']);
                array_pop($namePath);
                $namePath = implode($namePath, DS).DS.$data['user_name'];
                
                // 是否有同名目录
                $res = is_dir($namePath);
                if ($res) {
                    $this->ajaxError('存在相同目录，请重设！'.$namePath);
                    exit;
                }

                // 写入数据库
                $data['dir_path'] = $namePath;
                $res = db('c_customer')->update($data);

                if ($res === false) {
                    $this->ajaxError('操作失败');
                } else {
                    $this->ajaxSuccess('添加成功');
                }
                
                // 修改字符集
                $data['dir_path']= self::wChange($data['dir_path']);
                $namePath= self::wChange($namePath);
                // 修改目录名
                $resName = rename($data['dir_path'], $namePath);
                if (!$resName) {
                    $this->ajaxError('修改目录名失败，请尝试手动操作！'.$namePath);
                    exit;
                }
                // var_dump($namePath);
                // exit;

                //$data['password'] = user_md5($data['password']);
            }else{
                // 创建新用户
                // 用户名是否重复
                $has = db('c_customer')->where(array('user_name' => $data['user_name']))->count();
                if ($has) {
                    $this->ajaxError('用户名已经存在，请重设！');
                    exit;
                }

                // 判断密码是否为空
               if ($data['password'] === '' || $data['password'] === false || !$data['password']) {
                    // 生成字符串 MD5分享路径+随机字符串10个，打乱后，取前十位
                    $str = self::myRand(10);
                    $share_code = md5($rootPath).$str;
                    $share_code = substr(str_shuffle($share_code), 0, 10);
                    // 分享链接
                    $share_link = config('customer_root').DS.'share'.DS.$share_code;

                    if (config('sqlAddress')) {
                        // 调用sqlsrv接口
                        $NasUrl = urlencode($share_link);
                        $url = config('sqlAddress').'Cid='.$data['user_name'].'&NasUrl='.$NasUrl.'&NasPwd= ';
                        $sqlsrv_request = httpRequest($url, "POST" ,[], ['Content-length: 0']);
                        $sqlsrv_request = json_decode($sqlsrv_request, true);

                        // 判断返回值
                        // if ($sqlsrv_request['ResCode'] != '0000') {
                            // $this->ajaxError($sqlsrv_request['Msg']);
                            // exit;
                        // }else{
                            // 员工自建用户根目录
                            
                        // }
                    }
                    $rootPath = config('customer_folder');
                    // 年月  目录名
                    $datePath = date('Ym');
                    $data['dir_path'] = $rootPath.DS.$datePath.DS.$data['user_name'];
                    $dir_path = self::wChange($data['dir_path']);
                    $res = is_dir($dir_path);
                    // 用户目录存在报错，不存在，创建
                    if ($res) {
                        $this->ajaxError('用户名文件夹已经存在，请修改！');
                        exit;
                    }else{
                        @mkdir($dir_path,0777,true);
                    }

                    // 写用户表
                    $res = db('c_customer')->insert($data);
                    $uid = db('c_customer')->getLastInsID();

                    // 写入分享表
                    $sdata['share_code'] = $share_code;
                    $sdata['uid'] = $uid;
                    $res = db('c_share')->insert($sdata);
//                    else{
//                        $this->ajaxError('请设置sqlserver调用接口');
//                        exit;
//                    }
                // 用户设置密码,写用户表，不写分项表
                }else{
                    $res = db('c_customer')->insert($data);
                }
            }
            if ($res === false) {
                $this->ajaxError('操作失败');
            } else {
                $this->ajaxSuccess('添加成功');
            }
        // 编辑时，前端显示
        } else {
            $uid = input('uid/d');
            if($uid){
                $detail = db('c_customer')->where('id',$uid)->find();
                if($detail){
                    $this->assign('detail', $detail);
                }else{
                    $this->error('无效的客户编号');
                }
            }
            else{
                // 提交默认的用户、密码及真实姓名
                $uname = input('user_name/s');
                $detail = array(
                    'user_name'=> $uname,
                    'password' => '',
                    'nickname' => $uname
                );
                $this->assign('detail', $detail);
            }
            return $this->fetch();
        }
    }

    // 禁用用户
    public function close() {
        $id = I('post.id');
        $res = db('c_customer')->where(array('id' => $id))->update(array('status' => 0));
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    // 启用用户
    public function open() {
        $id = I('post.id');

        $res = db('c_customer')->where(array('id' => $id))->update(array('status' => 1));
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    // 删除用户
    public function del() {
        $uid = I('post.id');
        // $folder = ROOT_PATH.config('customer_folder').  md5($id);
        $customer = db('c_customer')->where('id',$uid)->find();
        // $folder = substr($customer['dir_path'],0,2)=='//' ? $customer['dir_path'] : ROOT_PATH.$customer['dir_path'];

        $folder = $customer['dir_path'];
        $folder = self::wChange($folder);

        if(file_exists($folder)){
            $fileRes = delDirAndFile($folder);
            if(!$fileRes){
                $this->ajaxError('操作失败');
                exit();
            }
        }
        
        $res = db('c_customer')->where(array('id' => $uid))->delete();
        // 删除用户所属分享链接
        db('c_share')->where(array('id' => $uid))->delete();
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    // 目录管理列表
    public function folderList() {
        
        $path = input('path');

        $path = str_replace(' ', '+', $path);
        $uid = input('uid');
        $customer = db('c_customer')->where('id',$uid)->find();
        if(!$customer){
            $this->error('没有此用户');
            exit();
        }
        if(substr($path, 0,1) == DS){
            $path = substr($path, 1);
        }
        $customer['path'] = $path;

        //路径导航
        $pathArr = explode(DS, $path);
        $tmp = '';
        $nav = array();
        foreach ((array)$pathArr as $pathStr){
            $tmp .= $pathStr;
            $nav[] = '<a href="folderlist.html?uid='.$uid.'&path='.$tmp.'">'.$pathStr.'</a>';
            $tmp .= DS;
        }

        if(!empty($nav)){
            $customer['nav'] = '<a href="folderlist.html?uid='.$uid.'&path='.DS.'">/</a>__'.implode('__', $nav);
        }

        // 如果没有用户目录
        if (!$customer['dir_path']) {
            // 员工自建用户根目录
            $rootPath = config('customer_folder');
            // 年月  目录名
            $datePath = date('Ym');
            $data['dir_path'] = $rootPath.DS.$datePath.DS.$customer['user_name'];
            $dir_path = $this->wChange($data['dir_path']);
            $res = is_dir($dir_path);
            // 用户目录存在报错，不存在，创建
            if ($res) {
                $this->error('用户名文件夹已经存在，请修改！'.$customer['dir_path']);
                exit;
            }else{
                @mkdir($dir_path,0777,true);
                $res = db('c_customer')->where('id',$uid)->update($data);
            }

            // // 第一层目录路径
            // $f = ROOT_PATH.config('customer_folder').DS.substr(md5($customer['user_name']), 0,2).DS;
            // // 第二层目录路径
            // $s = $f.substr(md5($customer['user_name']), 2,2).DS;
            // // 最终文件目录
            // $folder = $s.md5($customer['user_name']);

            // $str = explode(ROOT_PATH, $folder);
            // $data['dir_path'] = $str[1];
            // if($path == '' && !file_exists($folder)){
            //     // mkdir($f);
            //     // mkdir($s);
            //     // mkdir($folder);
            //     mkdir($folder,0777,true);
            //     // 将最终目录，存到数据库
            //     $res = db('c_customer')->where('id',$uid)->update($data);
            // }
        }else{
            // mkdir($customer['dir_path'],0777,true);
            $folder = $customer['dir_path'].DS.$path;
        }

        // 转换字符集
        $folder = self::wChange($folder);

        if(!file_exists($folder)){
            // mkdir($folder,0777,true);
            $this->error('找不到用户目录，可能用户目录不可写。'.$folder);
            exit();
        }
        $list = scandir($folder);
        // var_dump($folder);
        // exit;
        $fileList = array();
        
        foreach ($list as $dir){
            //echo $dir;
            if(substr($dir,0,1) == '.' || $dir == 'Thumbs.db'){
            // 过虑隐藏文件或.开头的文件
                continue;
            }

            if(is_dir($folder.DS.$dir)){
                // 判断字符集
                $encode = mb_detect_encoding($dir, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
                // 如果不是utf8，则转换成utf8
                if ($encode != "UTF-8"){
                    // $dir = iconv("UTF-8","GB2312//IGNORE",$dir); 
                    $dir = iconv("GBK","UTF-8",$dir); 
                }
                $fileList[] = ['name'=>$dir,'dir'=>1];
            }else{
                // 判断字符集
                $encode = mb_detect_encoding($dir, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
                // 如果不是utf8，则转换成utf8
                if ($encode != "UTF-8"){
                    // $dir = iconv("UTF-8","GB2312//IGNORE",$dir); 
                   $dir = iconv($encode,"UTF-8",$dir); 
                }
                $fileList[] = ['name'=>$dir,'dir'=>0];
            }
            
        }

        $this->assign('list',$fileList);
        // var_dump($customer);
        // exit;
        $this->assign('customer',$customer);
        
        return $this->fetch();
    }

    // 新增子目录
    public function folderAdd() {
        
        if (IS_POST) {
            $uid = input('uid');
            $parentFolder = input('parent_folder');
            
            $folderName = input('folder_name');

            if(strpos($folderName,'..') !== false || strpos($folderName,'\\') !== false ||strpos($folderName,'/') !== false || strpos($folderName,'*') !== false || strpos($folderName,'$') !== false){
                $this->error('无效的目录名,目录名不能包含特殊字符。');
                exit();
            }
            // 从数据库获取目录地址
            $customer = db('c_customer')->where('id',$uid)->find();
            // $folder = ROOT_PATH.$customer['dir_path'];
            // $folder = substr($customer['dir_path'],0,2)=='//' ? $customer['dir_path'].DS.$parentFolder : ROOT_PATH.$customer['dir_path'].DS.$parentFolder;
            $folder = $customer['dir_path'].DS.$parentFolder;
            // 转换字符集
            $folder = self::wChange($folder);
            $folderName = self::wChange($folderName);

            // $folder = ROOT_PATH.C('customer_folder').  md5($uid) .DS.$parentFolder;
            if(!file_exists($folder)){
                $this->error('无效的目录'.$folder);
                exit();
            }
            if(input('?post.old_folder_name')){
                //修改目录名
                $oldFolderName = input('old_folder_name');
                @rename($folder.$oldFolderName, $folder.$folderName);
                $this->ajaxSuccess('修改成功');
            }else{
                //添加目录
                @mkdir($folder.DS.$folderName,0777,true);
                $this->ajaxSuccess('创建成功');
            }
        }else{
            
            $uid = input('uid');
            $parentFolder = input('parent_folder');
            $detail = array(
                'uid'=>$uid,
                'parent_folder'=>$parentFolder,
            );
            if(input('?get.folder_name')){
                $detail['folder_name'] = input('folder_name');
            }
            // var_dump($parentFolder);
            // var_dump($detail);
            // exit;
            $this->assign('detail',$detail);
            
            return $this->fetch();
        } 
    }

    // 删除目录
    public function folderDel() {
        $uid = input('uid');
        $path = input('path');
        if(strpos($path,'..') !== false  || strpos($path,'*') !== false || strpos($path,'$') !== false){
            $this->error('无效的目录名.');
            exit();
        }

        if($path == '\\' || $path == '/' || $path == config('customer_folder') || $path == config('customer_user')){
            $this->error('根目录不可以删除。');
            exit();
        }

        if(substr($path, 0,1) == DS){
            $path = substr($path, 1);
        }
        // 从数据库获取目录地址
        $customer = db('c_customer')->where('id',$uid)->find();
        // $folder = ROOT_PATH.$customer['dir_path'].DS.$path;
        $folder = substr($customer['dir_path'],0,2)=='//' ? $customer['dir_path'].DS.$path : ROOT_PATH.$customer['dir_path'].DS.$path;
        // $folder = ROOT_PATH.C('customer_folder').  md5($uid) .DS.$path;
        //exit($folder);
        // 转换字符集
        $folder = self::wChange($folder);

        $res = delDirAndFile($folder);
        if($res){
            $this->ajaxSuccess('删除成功');
        }else{
            $this->error('删除失败'.$folder);
        }
    }

    // 上传文件(可执行文件除外)
    public function uploadFile() {
        
        if(\think\Request::instance()->isPost()){
            //接收文件
            $uid = input('get.uid');
            $parentFolder = urldecode(input('get.parent_folder'));
            //exit('uid:'.$uid.'=====p:'.$parentFolder);
            //die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            // $targetDir = ROOT_PATH.config('customer_folder').  md5($uid) .DS.$parentFolder;

            // 从数据库获取目录地址
            $customer = db('c_customer')->where('id',$uid)->find();
            // $folder = ROOT_PATH.$customer['dir_path'].DS.$parentFolder;
            $folder = substr($customer['dir_path'],0,2)=='//' ? $customer['dir_path'].'/'.$parentFolder : ROOT_PATH.$customer['dir_path'].DS.$parentFolder;

            // 转换字符集
            $targetDir = self::wChange($folder);
            
            //$targetDir = ini_get("upload_tmp_dir") . DS . "plupload";
            $cleanupTargetDir = true; // Remove old files
            $maxFileAge = 10 * 3600; // Temp file age in seconds


            // Create target dir
            if (!file_exists($targetDir)) {
                    @mkdir($targetDir);
            }
            
            // Get a file name
            if (isset($_REQUEST["name"])) {
                    $fileName = $_REQUEST["name"];
            } elseif (!empty($_FILES)) {
                    $fileName = $_FILES["file"]["name"];
            } else {
                    $fileName = uniqid("file_");
            }
            
            $fileName = self::wChange($fileName);
            $filePath = $targetDir . DS . $fileName;

            // Chunking might be enabled
            $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
            $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


            // Remove old temp files	
            if ($cleanupTargetDir) {
                    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                            die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
                    }

                    while (($file = readdir($dir)) !== false) {
                            $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                            // If temp file is current file proceed to the next
                            if ($tmpfilePath == "{$filePath}.part") {
                                    continue;
                            }

                            // Remove temp file if it is older than the max age and is not the current file
                            if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                                    @unlink($tmpfilePath);
                            }
                    }
                    closedir($dir);
            }	


            // Open temp file
            if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (!empty($_FILES)) {
                    if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                            die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
                    }

                    // Read binary input stream and append it to temp file
                    if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                    }
            } else {	
                    if (!$in = @fopen("php://input", "rb")) {
                            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                    }
            }

            while ($buff = fread($in, 4096)) {
                    fwrite($out, $buff);
            }

            @fclose($out);
            @fclose($in);

            // Check if file has been uploaded
            if (!$chunks || $chunk == $chunks - 1) {
                    // Strip the temp .part suffix off 
                    rename("{$filePath}.part", $filePath);
            }

            // Return Success JSON-RPC response
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
            
            
        }else{
            $size = getMaxUploadSize();
            
            
            $uid = input('uid');
            $parentFolder = urldecode(input('parent_folder'));
            $this->assign('uid', $uid);
            $this->assign('size', $size);
            $this->assign('parentFolder', $parentFolder);
            
            return $this->fetch();
        }
    }

    // 全部新增
    public function addAll() {
        $data = I('post.');
        $password = $data['password'];

        // 获取指定用户根目录
        $ur_path = db('config_customer')->where('id',1)->value('ur_path');

        // 转换字符集
        $ur_path_temp = self::wChange($ur_path);

        // $path = ROOT_PATH.config('customer_user').DS.$ur_path_temp;
        $path = substr(config('customer_user'),0,2)=='//' ? config('customer_user').'/'.$ur_path_temp : ROOT_PATH.config('customer_user').DS.$ur_path_temp;

        // 从用户自定义根目录中读取目录
        $list = scandir($path);

        $mark = '.sys';
        $i = 0;
        $root_dir = \think\Request::instance()->domain();
        foreach ($list as $key => $dir_temp){
            // 去掉根目录及隐藏目录
            if(substr($dir_temp,0,1) == '.'){
                continue;
            }
            // 判断字符集
            $encode = mb_detect_encoding($dir_temp, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
            // 如果不是utf8，则转换成UTF—8
            if ($encode != "UTF-8"){ 
                $dir = iconv("GBK","UTF-8",$dir_temp);
            }
            // var_dump($dir);
            // 拼接用户自定义目录路径
            // $str = ROOT_PATH . config('customer_user').DS.$ur_path_temp.DS.$dir_temp;
            $str = substr(config('customer_user'),0,2)=='//' ? config('customer_user').'/'.$ur_path_temp.'/'.$dir_temp : ROOT_PATH . config('customer_user').DS.$ur_path_temp.DS.$dir_temp;
            
            if (!file_exists($str.DS.$mark)) {
                $has = db('c_customer')->where(array('user_name' => $dir))->count();
                if (!$has) {
                    $data['user_name'] = $dir;
                    $data['password']  = $password;
                    $data['nickname']  = $dir;
                    $data['dir_path']  = config('customer_user').DS.$ur_path.DS.$dir;
                    $data['status']    = 1;

                    $rand = self::myRand(10);
                    $share_code = md5($data['dir_path']).$rand;
                    $share_code = substr(str_shuffle($share_code), 0, 10);
                    $share_link = config('customer_root').DS.'share'.DS.$share_code;

                    if (config('sqlAddress')) {
                        $NasUrl = urlencode($share_link);
                        $url = config('sqlAddress').'Cid='.$dir.'&NasUrl='.$NasUrl.'&NasPwd= ';
                        $sqlsrv_request = httpRequest($url, "POST" ,[], ['Content-length: 0']);
                        $sqlsrv_request = json_decode($sqlsrv_request, true);
                        // var_dump($sqlsrv_request);               
                        if ($sqlsrv_request['ResCode'] != '0000') {
                            $dirList[$key] = array('name'=>$dir, 'url' => $str, 'errMsg' => $sqlsrv_request['Msg']);
                        }else{
                            $res = db('c_customer')->insert($data);
                            $uid = db('c_customer')->getLastInsID();

                            // 创建标识文件
                            $counter_file = $str.DS.'.sys';
                            $fopen = fopen($counter_file, 'wb');

                            fputs($fopen, 'success');
                            fclose($fopen);

                            // 如没有密码 就设定分享链接
                            if ($password === '' || $password === false || !$password) {
                                $sdata['share_code'] = $share_code;
                                $sdata['uid'] = $uid;
                                $res = db('c_share')->insert($sdata);
                            }
                        }
                    }
                }else{
                    $dirList[$key] = array('name'=>$dir, 'url' => $str, 'msg' => 'error');
                }
            }
            $i++;
            if ($i>=1000) {
                break;
            }
        }
        return $dirList;
        // var_dump($dirList);
        // exit;
        // $this->assign('list', $dirList);
        // return $this->fetch('addlist');
    }

    // 新增单个
    public function addOne(){
        if (IS_POST) {
            $data = I('post.');
            $has = db('c_customer')->where(array('user_name' => $data['user_name']))->count();
            if ($has) {
                $this->ajaxError('用户名已经存在，请重设！');
            }

            // 获取用户指定的根目录
            $ur_path = db('config_customer')->where('id',1)->value('ur_path');
            // $user_path = ROOT_PATH.config('customer_user').DS.$ur_path.DS.$data['oldname'];
            $user_path = substr(config('customer_user'),0,2)=='//' ? config('customer_user').'/'.$ur_path.'/'.$data['oldname'] : ROOT_PATH.config('customer_user').DS.$ur_path.DS.$data['oldname'];
            $uData = array(
                'user_name'=> $data['user_name'], 
                'password' => $data['password'], 
                'nickname' => $data['nickname'], 
                'dir_path' => config('customer_user').DS.$ur_path.DS.$data['oldname']
            );
            // 转换字符集
            $user_path = self::wChange($user_path);
            
            if (!file_exists($user_path)) {
                $this->ajaxError('文件不存在'.$user_path);
            }

            $res = db('c_customer')->insert($uData);
            $uid = db('c_customer')->getLastInsID();

            if ($res === false) {
                $this->ajaxError('操作失败');
            }

            // 创建标识文件
            $counter_file = $user_path.DS.'.sys';
            $fopen = fopen($counter_file, 'wb');
            fputs($fopen, 'success');
            fclose($fopen);

            // 如没有密码 就设定分享链接
            if ($password === '' || $password === false || !$password) {
                // 生成字符串 MD5分享路径+随机字符串10个，打乱后，取前十位
                $str = self::myRand(10);
                $share_code = md5($data['dir_path']).$str;
                $sdata['share_code'] = substr(str_shuffle($share_code), 0, 10);
                $sdata['uid'] = $uid;
                $res = db('c_share')->insert($sdata);
                
                $shareList['share_link'] = config('customer_root').DS.'share'.DS.$sdata['share_code'];

                if (config('sqlAddress')) {
                    $cid = $dir;
                    $NasUrl = urlencode($shareList['share_link']);
                    $url = config('sqlAddress').'Cid='.$cid.'&NasUrl='.$NasUrl.'&NasPwd= ';
                    httpRequest($url, "POST" ,[], ['Content-length: 0']);
                }
            }

            $this->ajaxSuccess('添加成功');

        } else {
            // 提交默认的用户、密码及真实姓名
            $uname = input('user_name/s');
            $uname = urldecode($uname);
            $detail = array(
                'user_name'=> $uname,
                'password' => '',
                'nickname' => $uname
            );
            // var_dump($uname);
            // exit;
            $this->assign('detail', $detail);
            return $this->fetch();
        }        
    }

    // 刷新底片文档
    public function refresh() {

        // 获取指定用户根目录
        $ur_path = db('config_customer')->where('id',1)->value('ur_path');
        // 转换字符集
        // $ur_path = self::wChange($ur_path);
        
        // $path = ROOT_PATH.config('customer_user').DS.$ur_path;
        // 使用共享目录
        $path = substr(config('customer_user'),0,2)=='//'?config('customer_user').'/'.$ur_path:ROOT_PATH.config('customer_user').DS.$ur_path;
        // var_dump($path);
        $path = self::wChange($path);

        // 从用户自定义根目录中读取目录
        $list = scandir($path);
        // var_dump($path);
        // var_dump($list);
        // exit;
        // 统计目录数量
        $count = count($list);
        if ($count > 9990) {
            $this->assign('count', $count);
        }

        foreach ($list as $key => $dir){
            // 去掉根目录及隐藏目录
            if(substr($dir,0,1) == '.'){
                continue;
            }

            // 拼接用户自定义目录路径
            $mark = '.sys';
            $str = $path.DS.$dir;

            if (!file_exists($str.DS.$mark)) {
                // 判断字符集
                $encode = mb_detect_encoding($dir, array("ASCII","UTF-8","GB2312","GBK","BIG5"));
                // 如果不是utf8，则转换成utf8
                if ($encode != "UTF-8"){
                    // $dir = iconv("UTF-8","GB2312//IGNORE",$dir); 
                    $dir = iconv("GBK","UTF-8",$dir); 
                }

                // 判断dir目录字符，是否有特殊符号或者全角输入
                // $types = preg_replace("/([[:alnum:]]|[[:space:]]|[[:punct:]])+/U", '', $dir);
                // var_dump($types);
                
                if(preg_match("/[ '.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$dir)){
                    $bname = urlencode($dir);
                    $dirList[$key] = array('name'=>$dir, 'bname'=>$bname, 'err' => $str);
                } else{
                    $bname = urlencode($dir);
                    $dirList[$key] = array('name'=>$dir, 'bname'=>$bname);
                }
            }
        }
        // var_dump($dirList);
        // exit;
        $dir = db('config_customer')->where('id',1)->value('ur_path');
        $this->assign('dir', $dir);
        $this->assign('list', $dirList);
        return $this->fetch('freshlist');
    }

    // 根据用户名搜索
    public function search() {
        $keyword = input('post.keyword');
        if (!$keyword) {
            $this->error('用户名不能为空');
        }
        
        $listInfo = db('c_customer')->where('user_name', $keyword)->paginate(50);
        $this->assign('list', $listInfo);
        // var_dump($listInfo);
        // exit;
        return $this->fetch('index');
    }

    // 指定用户根目录
    public function setDir(){
        $dir = input('post.dir');
        if (!$dir) {
            $this->error('目录名不能为空');
        }
        if(strpos($dir,'..') !== false || strpos($dir,'\\') !== false ||strpos($dir,'/') !== false || strpos($dir,'*') !== false || strpos($dir,'$') !== false){
            $this->error('无效的目录名,目录名不能包含特殊字符。');
            exit();
        }

        $data['ur_path'] = $dir;
        $res = db('config_customer')->where('id', 1)->update($data);

        if ($res === false) {
            $this->error('设置失败，请重试！');
            exit();
        }
        // 转换字符集
         
        // 如果目录不存在，创建新目录
        $mdir = substr(config('customer_user'),0,2)=='//'?config('customer_user').'/'.$dir:ROOT_PATH.config('customer_user').DS.$dir;
        $mdir = self::wChange($mdir);
        if (!file_exists($mdir)) {
            $resss = mkdir($mdir, 0777, true);
            if (!$resss) {
                # code...
                $this->error('设置失败，请重试！'.$mdir);
                exit();
            }
        }
        $this->Success('设置成功');
    }

    // 分享目录列表
    public function shareList(){

        $uid = input('uid');
        // 查询
        $customer = db('c_customer')->where('id', $uid)->find();
        $share = db('c_share')->where('uid', $uid)->find();
        // 获取当前域名
        // $root_dir = \think\Request::instance()->domain();
        
        $shareList = array();
        // 如果没有分享信息
        if (!$share) {
            // 密码为空
            if ($customer['password'] === '' || $customer['password'] === false || !$customer['password']) {
                $root_dir = \think\Request::instance()->domain();
                // 分享码为空
                if (empty($share['share_code'])) {
                    // 生成字符串 MD5分享路径+随机字符串10个，打乱后，取前十位
                    $str = self::myRand(10);
                    $share_code = md5($customer['dir_path']).$str;
                    $data['share_code'] = substr(str_shuffle($share_code), 0, 10);
                    $data['uid'] = $uid;
                    $res = db('c_share')->insert($data);
                    $shareList['share_path'] = $customer['dir_path'];
                    $shareList['share_link'] = config('customer_root').DS.'share'.DS.$sdata['share_code'];

                    if (config('sqlAddress')) {
                        $cid = explode(DS,$customer['dir_path']);
                        $cid = array_pop($cid);

                        $NasUrl = urlencode($shareList['share_link']);
                        
                        $url = config('sqlAddress').'Cid='.$cid.'&NasUrl='.$NasUrl.'&NasPwd= ';
                        $res = httpRequest($url, "POST" ,[], ['Content-length: 0']);
                    }

                    // 写入sqlserver数据库
                    // $res = db('user','db_sqls')->insert($data);
                    // $shareList['share_link'] = $root_dir.'/share/'.$data['share_code'];
                }
                // else{
                //     $shareList['share_path'] = $customer['dir_path'];
                //     $shareList['share_link'] = config('customer_root').DS.'share'.DS.$share['share_code'];
                // }
            }
        }else{
            $shareList['share_path'] = $customer['dir_path'];
            // $shareList['share_link'] = $root_dir.url('index/share', ['action' => $share['share_code']]);
            $shareList['share_link'] = config('customer_root').DS.'share'.DS.$share['share_code'];
        }
        

        $this->assign('customer',$customer);
        $this->assign('shareList',$shareList);
        return $this->fetch();
    }

    // 随机字符串
    static function myRand($len){
        $chars='ABCDEFGHJKLMNPQRSTUVWXY1234567890abcdefghjkmnpqrstuvwxyz';
        $string=time();
        for(;$len>=1;$len--){
            $position=rand()%strlen($chars);
            $position2=rand()%strlen($string);
            $string=substr_replace($string,substr($chars,$position,1),$position2,0);
        }
        return $string;
    }

    // 判断是否是windows系统，如果是，则转换字符集
    static function wChange($str){
        // 如果是windows系统，则转换字符集
        if (strtoupper(substr(php_uname(),0,3)) == 'WIN') {
            $str = iconv("UTF-8","GB2312//IGNORE",$str);
        }
        return $str;
    }

}